package com.mediacloud.app.newsmodule.fragment


import android.content.Context
import android.graphics.Color
import android.graphics.Typeface
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.annotation.RequiresApi
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager.widget.ViewPager
import com.blankj.utilcode.util.NetworkUtils
import com.donkingliang.consecutivescroller.ConsecutiveScrollerLayout
import com.eventTrack.CDPTrackReportManager
import com.eventTrack.TXReportManager
import com.flyco.tablayout.SlidingTabLayout
import com.flyco.tablayout.listener.OnTabSelectListener
import com.google.gson.Gson
import com.mediacloud.app.adapter.ComponentRecyclerAdapter
import com.mediacloud.app.assembly.util.Utility
import com.mediacloud.app.assembly.util.isFastClick
import com.mediacloud.app.assembly.util.loadX
import com.mediacloud.app.fbnavsk.SecondNav
import com.mediacloud.app.fbnavsk.navPaddingTopMatch
import com.mediacloud.app.model.OnVideoPlayerPause
import com.mediacloud.app.model.component.ComponentItem
import com.mediacloud.app.model.interfaces.DataInvokeCallBack
import com.mediacloud.app.model.news.ArticleListData
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.model.news.ShowSwitch
import com.mediacloud.app.model.news.kt.TypeX
import com.mediacloud.app.model.view.floatwin.FloatButtonGroup
import com.mediacloud.app.nav2.fragment.HqyNavFragment
import com.mediacloud.app.newsmodule.BuildConfig
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.adaptor.component.ComponentHolder
import com.mediacloud.app.newsmodule.adaptor.component.ComponentListItemStyleAdaptor
import com.mediacloud.app.newsmodule.adaptor.component.IExposure
import com.mediacloud.app.newsmodule.fragment.video.vod.PlayClickListener
import com.mediacloud.app.newsmodule.fragment.video.vod.VideoListPlayerUtil
import com.mediacloud.app.newsmodule.utils.NewsItemClickUtils
import com.mediacloud.app.newsmodule.utils.NewsListDataInvoker
import com.mediacloud.app.newsmodule.utils.readData
import com.mediacloud.app.newsmodule.utils.saveData
import com.mediacloud.app.reslib.enums.GlobalSwitch
import com.mediacloud.app.reslib.enums.ToolBarActionF5OrTop
import com.mediacloud.app.reslib.enums.XKey
import com.mediacloud.app.reslib.util.DataInvokeUtil
import com.scwang.smartrefresh.layout.api.RefreshFooter
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import com.scwang.smartrefresh.layout.listener.SimpleMultiPurposeListener
import com.tencent.mmkv.MMKV
import com.utils.ExposurePoolService
import com.utils.InflateTimeLogTools
import com.zimeiti.activity.MConsecutiveViewPager
import com.zimeiti.activity.TabListFragment
import com.zimeiti.activity.TabWaterfallFragment
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.component_type89.*
import kotlinx.android.synthetic.main.fragment_blank_page.*
import kotlinx.android.synthetic.main.fragment_service_navigation.*
import org.greenrobot.eventbus.EventBus
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread
import org.json.JSONException
import org.json.JSONObject
import java.util.*
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.Future
import java.util.concurrent.atomic.AtomicInteger
import kotlin.collections.set


/**
 * 强军号
 */
class NewBlankPageFragment : HqyNavFragment(), OnRefreshLoadMoreListener,
    DataInvokeCallBack<ArticleListData>, ToolBarActionF5OrTop {

    val titles: MutableList<String> = ArrayList()
    var catalogs: MutableList<CatalogItem> = ArrayList()
    val fragments: MutableList<Fragment> = ArrayList()
    var adapter: PagerAdapter? = null
    var catalogID: String? = null
    var componentAdapter: ComponentListItemStyleAdaptor? = null
    var catalogItem: CatalogItem? = null
    var dataInvoker: NewsListDataInvoker? = null
    var tabComponentItem: ComponentItem? = null
    var c89Item: ComponentItem? = null
    var c89ContentItem: MutableList<ComponentItem>? = null

    var mConsecutiveViewPager: MConsecutiveViewPager? = null
    var adapterComponent: ComponentRecyclerAdapter<ComponentItem>? = null
    var moreViews: CopyOnWriteArrayList<View> = CopyOnWriteArrayList()
    var moreViewsCache: CopyOnWriteArrayList<View> = CopyOnWriteArrayList()
    private var nowCount: AtomicInteger = AtomicInteger(0)
    private var nowCountCache: AtomicInteger = AtomicInteger(0)
    var syncCount = 0
    var syncCountCache = 0
    var syncLock = false
    var futureTasks = ArrayList<Future<Unit>>();

    var tempTabName: String? = null
    var titleName: String? = null
    var  mTab: String?=null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //  String TAG = getClass().getCanonicalName();
        mTab = TXReportManager.getInstance().firstTabInfo.tabName
    }
    override fun getLayoutResID(): Int {
        return R.layout.fragment_blank_page
    }

    override fun initArgs() {
        super.initArgs()
        if (fragmentArguments != null) {
            saveInstanceArguments = fragmentArguments
            catalogID = saveInstanceArguments?.getString("id")
            catalogItem = saveInstanceArguments?.getParcelable("catalog")
        } else if (saveInstanceArguments != null) {
            catalogID = saveInstanceArguments!!.getString("id")
            catalogItem = saveInstanceArguments!!.getParcelable("catalog")
        }
        futureTasks.clear();
    }

    override fun initOther() {
        super.initOther()
        componentAdapter = ComponentListItemStyleAdaptor(requireContext(), catalogItem)

        dataInvoker = NewsListDataInvoker(this)
        refreshLayout.setOnMultiPurposeListener(object : SimpleMultiPurposeListener() {
            override fun onFooterMoving(
                    footer: RefreshFooter,
                    isDragging: Boolean,
                    percent: Float,
                    offset: Int,
                    footerHeight: Int,
                    maxDragHeight: Int
            ) {
                scroller.stickyOffset = offset
            }
        })

        scroller.onVerticalScrollChangeListener =
            ConsecutiveScrollerLayout.OnScrollChangeListener { v, scrollY, oldScrollY, scrollState ->
                if (scrollState == ConsecutiveScrollerLayout.SCROLL_STATE_IDLE) {
                    app_jhapp_home_subtab_content_imp()
                }

                }

    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        navPaddingTopMatch()

    }

    override fun choosed() {
        super.choosed()
        if(isAdded){
            app_jhapp_home_subtab_content_imp()
        }
    }

    override fun unChosoed() {
        super.unChosoed()
        EventBus.getDefault().post(OnVideoPlayerPause())
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        setComponentItemsVisibleHint();
    }
    override fun onResume() {
        super.onResume()
        mResume = true;
        setComponentItemsVisibleHint();
    }

    var mVideoListPlayerUtil: VideoListPlayerUtil? = null

    var playClickListener =
        PlayClickListener { rootView, container, playIcon, item ->
            if (mVideoListPlayerUtil == null) {
                mVideoListPlayerUtil = VideoListPlayerUtil(
                    activity,
                    scroller,
                    this@NewBlankPageFragment
                )
                mVideoListPlayerUtil!!.hqyNavFragment = this@NewBlankPageFragment
                if (parentFragment is SecondNav) {
                    mVideoListPlayerUtil!!.mPlayer.viewPlayer =
                        (parentFragment as SecondNav?)!!.viewPager
                }
            }
            if (item != null && mVideoListPlayerUtil!!.item != null && mVideoListPlayerUtil!!.getPlayer() != null && mVideoListPlayerUtil!!.item == item && mVideoListPlayerUtil!!.getPlayer().isPlaying
            ) {
                return@PlayClickListener
            }
            mVideoListPlayerUtil!!.setPlayerContainer(container,
                container,
                playIcon,
                !TextUtils.isEmpty(item.goodsID),
                {
                    item.parentId = catalogID
                    NewsItemClickUtils.OpenItemNewsHandle(
                        activity,
                        item.getType(),
                        item,
                        catalogItem
                    )
                },
                item
            )
            mVideoListPlayerUtil!!.isAutoPlayVideo = item.getType() == TypeX.NEWS.MICRO_DYNAMIC
            mVideoListPlayerUtil!!.setVideoDetail(catalogID + "", item)
        }

    override fun initToRefresh() {
        if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
            return
        }
        InflateTimeLogTools.inflateTimeLogTools(
            "initToRefresh-start-wait",
            System.currentTimeMillis(),
            0,
            0,
            javaClass
        )

        var task = doAsync {
            val dataResult = readData("$catalogID", ArticleListData::class.java)
            uiThread {
                InflateTimeLogTools.inflateTimeLogTools(
                    "initToRefresh-start-now",
                    System.currentTimeMillis(),
                    0,
                    0,
                    javaClass
                )
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    mActivity?.mainLooper?.queue?.addIdleHandler {
                        doDataTask(dataResult)
                        false
                    }
                }else{
                    doDataTask(dataResult)
                }

            }
        }
        futureTasks.add(task);
    }

    private fun doDataTask(dataResult : ArticleListData?){
        if (dataResult != null && (dataResult.articleList.size > 0 || dataResult.componentItems.size > 0)) {
            success(dataResult)
        } else {
            getData()
        }
    }

    private fun getData() {
        dataInvoker?.getContentList(catalogID, 1, 1, null)
        InflateTimeLogTools.fragmentTimeLogTools("getDataFromNet",System.currentTimeMillis(),javaClass)
    }

    var oldVerticalOffset: Int = 0
    override fun initView() {
        loadingView = findViewById(R.id.mLoadingView);
        initStateView();
        retryTips?.setOnClickListener {
            if (currentState != TYPE_LOADING) {
                if (NetworkUtils.isConnected()) {
                    showStateView(TYPE_LOADING, false)
                    onRefresh(refreshLayout)
                }
            }
        }
        showStateView(TYPE_LOADING, false)
        refreshLayout.setOnRefreshLoadMoreListener(this)
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        EventBus.getDefault().post(OnVideoPlayerPause())
        getData()
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        mConsecutiveViewPager?.let {
            val index = it.currentItem
            if (fragments != null && fragments.size > index) {
                val f = fragments[index]
                if (f is OnLoadMoreListener) {
                    f.onLoadMore(refreshLayout)
                }
            }
        }

    }

    override fun onPause() {
        super.onPause()
        mResume = false;
        setComponentItemsVisibleHint();
    }
    var mArticleListData: ArticleListData? = null
    var realVisible: Boolean? = null
    var mResume = false
    public fun setComponentItemsVisibleHint(){
        if (mArticleListData != null && mArticleListData?.componentItems != null && mArticleListData!!.componentItems.size > 0) {
            var newVisible:Boolean = getUserVisibleHint() && isVisible() && mResume;
            if (realVisible != null && realVisible!!.equals(newVisible) ) {
                return;
            } else {
                realVisible = newVisible;
            }
            /*if (catalogItem != null) {
                Log.d("tag", "sssssssssssss" + catalogItem?.getName() + "-" + newVisible);
            } else {
                Log.d("tag", "sssssssssssss" + catalogID + "-" + newVisible);
            }*/
            mArticleListData?.componentItems?.forEach {
                it.realVisible = newVisible
                if (mTab != null) {
                    it.tabName = mTab;
                }
            }
        }
    }

    var oldMd5 = ""

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun success(data: ArticleListData?) {
        if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
            return
        }
        mArticleListData=data
        realVisible = null;
        setComponentItemsVisibleHint();
        //活动查询成功，上报
        if (catalogID == "1332" || catalogID == "1958") {
            TXReportManager.getInstance().activity_query()
        }

        if (syncLock) {
            refreshLayout.finishRefresh();
            return
        } else {
            refreshLayout.setEnableLoadMore(false)
            syncLock = true
        }
        if (data?.orginData != null) {
            val mdata: JSONObject = data.orginData.optJSONObject("data")!!
            if (FloatButtonGroup.haveFloatField(mdata)) {
                initFloatWin(mdata)
            } else {
                hideFloatWin()
            }
        }
        //不是上次的缓存数据才进行缓存
        val isCacheData = data?.orginData?.optInt("is_cache", 0) == 1
        if (!isCacheData) {
            try {
                data?.orginData?.put("is_cache", 1)
                doAsync {
                    saveData("$catalogID", data?.orginData.toString() + "")
                }
            } catch (e: JSONException) {
                e.printStackTrace()
            }
        }
        refreshLayout.finishRefresh()
        var startTime = System.currentTimeMillis()
        if (data?.state == true) {

            val componentList = data.componentItems

            //  componetContainer.updateComponent(result.componentItems);
            for (i in componentList.indices) {
                componentList[i].belongNavId = catalogID
            }
            tabComponentItem = null
            componentAdapter?.playClickListener = playClickListener
            componentAdapter?.listContentData = componentList
            componentAdapter?.clearEvent()
            val size = componentList.size
            if(isCacheData){
                syncCountCache = 0
                moreViewsCache.clear()
            }else{
                syncCount = 0
                moreViews.clear()
            }
            for (index in 0 until size) {
                val item = componentList[index]
                if (item.widget == TypeX.COMPONENT_X.C999912 || item.widget == TypeX.COMPONENT_X.C999988) {
                    break
                }

                if (item.widget != TypeX.COMPONENT_X.C999989 && c89Item == null) {
                    if(isCacheData){
                        syncCountCache++
                        moreViewsCache.add(null)
                    }else{
                        syncCount++
                        moreViews.add(null)
                    }
                }
            }
            if(isCacheData){
                nowCountCache.set(0)
            }else{
                nowCount.set(0)
            }

            for (index in 0 until size) {
                var startTimeEach = System.currentTimeMillis()
                val item = componentList[index]

                if (item.widget == TypeX.COMPONENT_X.C999912 || item.widget == TypeX.COMPONENT_X.C999988) {
                    tabComponentItem = item
                    //单独12，88控件时处理
                    if(size == 1){
                        afterAsyncLoadUI(isCacheData)
                    }
                    break
                }
                if (item.widget == TypeX.COMPONENT_X.C999989 || c89Item != null) {
                    if (c89Item == null) {
                        c89Item = item
                        c89ContentItem = ArrayList()
                    } else {
                        c89ContentItem?.add(item)
                    }
                    //单独89控件时处理
                    if(size == 1){
                        afterAsyncLoadUI(isCacheData)
                    }
                } else {
                    var task = doAsync {
                        if(isCacheData){
                            try {
                                moreViewsCache[index] = componentAdapter?.getView(index, null, null)
                            }catch (e: Exception) {
                                e.printStackTrace()
                            }finally {
                                nowCountCache.addAndGet(1);
                            }

                            if(nowCountCache.get() == syncCountCache){
                                uiThread {
                                    afterAsyncLoadUI(isCacheData)
                                }
                            }

                        }else{
                            try {
                                moreViews[index] = componentAdapter?.getView(index, null, null)
                            }catch (e: Exception) {
                                e.printStackTrace()
                            }finally {
                                nowCount.addAndGet(1);
                            }

                            if(nowCount.get() == syncCount){
                                uiThread {
                                    afterAsyncLoadUI(isCacheData)
                                }
                            }
                        }
                    }
                    futureTasks.add(task);
                }
                InflateTimeLogTools.fragmentTimeLogTools(
                        "success-for-each" + "widget:" + item.widget + " title:" + item.title,
                        startTimeEach,
                        javaClass
                )
            }
            InflateTimeLogTools.fragmentTimeLogTools("success-for-all", startTime, javaClass)

            cachArticleItem.clear()
            ids.delete(0, ids.length)
            componentContainer?.let {
                val childCount = componentContainer.getContainer().childCount
                try {
                    for (i in 0 until childCount) {
                        val itemView: View = componentContainer.getContainer().getChildAt(i)
                        var tag: Any? = itemView.getTag(R.id.component3_viewholder)
                        if (tag == null) {
                            tag = itemView.tag
                        }
                        if (tag != null) {
                            if (tag is IExposure) {
                                val componentItem = tag.exposureComponentItem
                                if (componentItem != null) {
                                    val jsonObject = JSONObject(componentItem.getOrginData())
                                    val jsonArray = jsonObject.getJSONArray("element")
                                    for (d in 0 until jsonArray.length()) {
                                        val articleItem = JSONObject(jsonArray[d].toString())
                                        if (articleItem.getString("type") == "1" && cachArticleItem.size < 10) {
                                            if(!articleItem.isNull("id")){
                                                if (ids.toString().isNotEmpty()) {
                                                    ids.append("," + articleItem.getLong("id"))
                                                } else {
                                                    ids.append(articleItem.getLong("id"))
                                                }
                                                cachArticleItem.add(articleItem)
                                            }
                                        }
                                    }

                                }

                            }
                        }
                    }
                    setContentData(ids.toString())

                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
    }
    private val cachArticleItem = arrayListOf<JSONObject>()
    private val ids = StringBuffer()

    protected fun setContentData(ids: String) {
        val params: MutableMap<String, String> = HashMap()
        params["article_id"] = ids //获取文稿的详情信息
        DataInvokeUtil.ziMeiTiApi.getArticleContent(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Observer<JSONObject?> {
                    override fun onSubscribe(d: Disposable) {}
                    override fun onNext(jsonObject: JSONObject) {
                        if (jsonObject.optBoolean("state")) {
                            val data = jsonObject.optJSONArray("data")
                            for (i in 0 until data.length()) {
                                try {
                                    val json = JSONObject(data[i].toString())
                                    val article_id = json.optString("article_id")
                                    val content = json.optString("content")
                                    for (j in cachArticleItem.indices) {
                                        if (article_id == cachArticleItem[j].optString("id")) {
                                            cachArticleItem[j].put("content", content)
                                        }
                                    }
                                } catch (e: java.lang.Exception) {
                                    e.printStackTrace()
                                }
                            }
                            MMKV.mmkvWithID(catalogID).clearAll()
                            val s = Gson().toJson(cachArticleItem)
                            MMKV.mmkvWithID(catalogID).putString(XKey.DETAIL_CACHE, s)
                        }
                    }

                    override fun onError(e: Throwable) {}
                    override fun onComplete() {}
                })
    }


    private fun afterAsyncLoadUI(isCacheData:Boolean){
        if(scroller == null){
            return
        }
        futureTasks.clear()
        //  scroller.removeAllViews()
        if(scroller.childCount>1){
            //不要移除componentContainer
            scroller.removeViews(1,scroller.childCount-1)
        }
        val time1 = System.currentTimeMillis()
        if(isCacheData){
            componentContainer.reset()
            for (moreView in moreViewsCache) {
                moreView?.let {
                    componentContainer.addView(moreView)
                }
            }
            componentContainer.notifyDataSetChanged()
            Log.e("wytest", "isCacheData："+(System.currentTimeMillis()-time1))
        }else{
            componentContainer.reset()
            for (moreView in moreViews) {
                moreView?.let {
                    val parent = moreView.parent
                    if (parent is ViewGroup) {
                        parent.removeView(moreView)
                    }
                    componentContainer.addView(moreView)
                }
            }
            componentContainer.notifyDataSetChanged()
            Log.e("wytest", "noCacheData:"+(System.currentTimeMillis()-time1))
        }
        closeStateView()
        c89Item?.let {
            setComponent89(it, c89ContentItem!!)
        }
        tabComponentItem?.let {
            if (!isCacheData) {
                buildTab(it)
            }
        }
        if (!isCacheData && tabComponentItem == null) {
            refreshLayout.finishLoadMoreWithNoMoreData()
        }
        syncLock = false
        if (isCacheData) {
            onRefresh(refreshLayout)
        }
        dataReady = true
        if(hadChoosed){
            app_jhapp_home_subtab_content_imp()
        }
    }

    override fun fault(data: Any?) {
        if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
            return
        }
        refreshLayout.finishRefresh(false)
        refreshLayout.setEnableLoadMore(false)

        if (componentAdapter != null && componentAdapter!!.listContentData != null && componentAdapter!!.listContentData!!.size > 0) {
            closeStateView()
        } else {
            showStateView(TYPE_NET_NOT_GIVE_FORCE, false)
        }
    }

    var tabView:View? = null
    private fun buildTab(componentItem: ComponentItem) {
        refreshLayout?.setEnableLoadMore(true)
        titles.clear()
        catalogs.clear()
        fragments.clear()
//        val layoutId = if (componentItem.widget == TypeX.COMPONENT_X.C999988){
//            R.layout.item_componentt_tab2
//        }else{
//            R.layout.item_componentt_tab
//        }
        //都不要吸顶  http://devops.test.chinamcloud.com/project/129/issue#statusId=28+30&assignedToIds=73255&filterType=Basic&type=Bug&openTaskId=10946
        val layoutId = R.layout.item_component_tab
        tabView = LayoutInflater.from(requireContext()).inflate(layoutId, scroller, true)
        tabView?.let{ view->
            val tabImage: ImageView = view.findViewById(R.id.tabImage)
            val tabContainer: View = view.findViewById(R.id.tabContainer)
            val tabLayout: SlidingTabLayout = view.findViewById(R.id.tabLayout)

            mConsecutiveViewPager = view.findViewById(R.id.mConsecutiveViewPager)

            val tabImageLp = tabImage.layoutParams as ViewGroup.MarginLayoutParams
            tabImageLp.height = resources.getDimensionPixelSize(R.dimen.dimen40)
            tabContainer.setBackgroundColor(Color.WHITE)

            var componentItemNew = componentItem.componentItemNew
            var otherField = componentItemNew.other_field
            var fontSize = 20
            var width_as_screen = false
            try {
                otherField?.let {
                    val font_default_color = otherField.font_default_color
                    val font_selected_color = otherField.font_selected_color
                    val selected_color = Color.parseColor(font_selected_color)
                    tabLayout.textUnselectColor = Color.parseColor(font_default_color)
                    tabLayout.textSelectColor = selected_color
                    val is_selected_underline = otherField.is_selected_underline

                    val font_default_size = otherField.font_default_size?: 20
                    val font_selected_size = otherField.font_selected_size?: 20
                    fontSize = font_selected_size
                    tabLayout.textsize = font_default_size.toFloat()
                    if (is_selected_underline == 0) {
                        tabLayout.indicatorHeight = 0f
                    } else {
                        tabLayout.indicatorColor = selected_color
                        tabLayout.indicatorHeight = 3f
                    }

                    tabLayout.setOnTabSelectListener(object : OnTabSelectListener {
                        override fun onTabSelect(position: Int) {
                            EventBus.getDefault().post(OnVideoPlayerPause())
                            for (i in 0 until tabLayout.getTabCount()) {
                                val textView: TextView = tabLayout.getTitleView(i)
                                if (position == i) {
                                    textView.textSize = font_selected_size.toFloat()
                                    textView.typeface = Typeface.DEFAULT_BOLD
                                } else {
                                    textView.textSize = font_default_size.toFloat()
                                    textView.typeface = Typeface.DEFAULT
                                }
                            }
                        }

                        override fun onTabReselect(position: Int) {}
                    })



                    if (componentItemNew.widget == TypeX.COMPONENT_X.C999912) {
                        val bg_img = otherField.bg_img
                        if (!TextUtils.isEmpty(bg_img)) {
                            tabImage.loadX(bg_img, 3, 0, false)
                        }

                        width_as_screen = otherField.width_as_screen == 1
                        if (!width_as_screen) {
                            val margin = resources.getDimensionPixelSize(R.dimen.dimen12)
                            tabImageLp.marginStart = margin
                            tabImageLp.marginEnd = margin
                        }
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            if (componentItemNew.widget == TypeX.COMPONENT_X.C999912) {
                val w = Utility.getScreenWidth(requireContext())
                if (width_as_screen) {
                    tabImageLp.width = w
                    tabImageLp.height = w * componentItemNew.height / componentItemNew.width
                } else {
                    tabImageLp.width = w - 2 * resources.getDimensionPixelSize(R.dimen.dimen12)
                    tabImageLp.height = tabImageLp.width * componentItemNew.height / componentItemNew.width
                }
            }
            tabImage.layoutParams = tabImageLp


            val elements = componentItemNew.elementTypeAs
            try {
                var showSwitch: ShowSwitch? = null
                for (i in 0 until elements.size) {
                    elements[i]?.let { element ->
                        val item = CatalogItem()
                        val name = element.title
                        item.catname = name

                        val navigate = element.navigate;
                        navigate?.let { navigate ->
                            item.catid = navigate.id
                            item.catalog_type = navigate.category
                        }
                        if (showSwitch == null) {
                            showSwitch = ShowSwitch()
                            /**
                             * tab绑定导航下新增show_switch对象，该对象下字段：
                             *  show_hit_count  是否显示浏览量
                             *  show_publish_date  是否显示日期
                             *  show_source  是否显示来源
                             *  show_comment  是否显示评论数
                             *  show_interaction_count 是否显示互动数
                             */
                            showSwitch?.let { showSwitch ->
                                if (navigate != null && navigate.show_switch != null) { //绑定导航的开关
                                    showSwitch.allowShowHitCount =
                                        navigate.show_switch.show_hit_count
                                    showSwitch.allowShowPublishDate =
                                        navigate.show_switch.show_publish_date
                                    showSwitch.allowShowSource =
                                        navigate.show_switch.show_source
                                    showSwitch.allowShowComment =
                                        navigate.show_switch.show_comment
                                    showSwitch.allowShowInteractionCount =
                                        navigate.show_switch.show_interaction_count
                                } else if (componentItem.mShowSwitch != null) { //所在导航的开关
                                    showSwitch.allowShowHitCount =
                                        componentItem.mShowSwitch.allowShowHitCount
                                    showSwitch.allowShowPublishDate =
                                        componentItem.mShowSwitch.allowShowPublishDate
                                    showSwitch.allowShowSource =
                                        componentItem.mShowSwitch.allowShowSource
                                    showSwitch.allowShowComment =
                                        componentItem.mShowSwitch.allowShowComment
                                    showSwitch.allowShowInteractionCount =
                                        componentItem.mShowSwitch.allowShowInteractionCount
                                } else { //默认
                                    showSwitch.allowShowHitCount = GlobalSwitch.allowShowHitCount
                                    showSwitch.allowShowPublishDate =
                                        GlobalSwitch.allowShowPublishDate
                                    showSwitch.allowShowSource = GlobalSwitch.allowShowSource
                                    showSwitch.allowShowComment = GlobalSwitch.allowShowComment
                                    showSwitch.allowShowInteractionCount =
                                        GlobalSwitch.allowShowInteractionCount
                                }
                            }
                        }
                        element.setmShowSwitch(showSwitch);
                        titles.add(name)
                        catalogs.add(item)
                        if (componentItem.widget == TypeX.COMPONENT_X.C999988) {
                            fragments.add(TabWaterfallFragment.newInstance(item.catid, item/*, d*/))
                        } else {
                            fragments.add(TabListFragment.newInstance(item.catid, item/*, d*/))
                        }
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            if(!titles.isNullOrEmpty()){
                tempTabName = titles[0]
            }
            mConsecutiveViewPager?.offscreenPageLimit = fragments.size
            adapter = PagerAdapter(fragments, titles, childFragmentManager)
            mConsecutiveViewPager?.adapter = adapter
            mConsecutiveViewPager?.setNoScroll(true)
            tabLayout.setViewPager(mConsecutiveViewPager)
            tabLayout.getTitleView(0).setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize.toFloat())
            tabLayout.getTitleView(0).typeface = Typeface.DEFAULT_BOLD
            mConsecutiveViewPager?.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
                override fun onPageScrolled(
                    position: Int, positionOffset: Float, positionOffsetPixels: Int
                ) {
                }

                override fun onPageSelected(position: Int) {
                    var currentTab = titles[position]
                    currentTab?.let{
                        TXReportManager.getInstance().app_jhapp_home_lrnarm_ctgy2_swh(tempTabName,currentTab)
                    }
                    tempTabName = currentTab;
                    val f = fragments[position]
                    if (f is TabListFragment) {
                        refreshLayout?.setNoMoreData(!f.hasMore)
                    } else if (f is TabWaterfallFragment) {
                        refreshLayout?.setNoMoreData(!f.hasMore)
                    }

                }

                override fun onPageScrollStateChanged(state: Int) {
                }
            })
            if (componentItemNew.widget == TypeX.COMPONENT_X.C999988) {
                mConsecutiveViewPager?.setNoScroll(false)
                if (titles.size <= 1) {
                    tabContainer.visibility = View.GONE
                } else {
                    tabContainer.visibility = View.VISIBLE
                }
            }
        }
    }

    private var component89View:View? = null;
    var recyclerView2:RecyclerView? = null
    private fun setComponent89(
        componentItem: ComponentItem, contentList: MutableList<ComponentItem>
    ) {
        refreshLayout.setEnableLoadMore(false)
        component89View =
            LayoutInflater.from(requireContext()).inflate(R.layout.component_type89, scroller, true)
        component89View?.let {component89View ->
            val girdView: GridView = component89View.findViewById(R.id.gridView)
            val tabContainer: FrameLayout = component89View.findViewById(R.id.tabContainer)
            val spanCount = componentItem.getCol()
            girdView.numColumns = spanCount
            val adapter = Adapter(requireContext())
            gridView.adapter = adapter
            adapterComponent = ComponentRecyclerAdapter(requireContext())
            adapterComponent?.catalogItem = catalogItem
            recyclerView2 = component89View.findViewById(R.id.recyclerView2)
            val layoutManager = LinearLayoutManager(requireContext())

            recyclerView2?.let{recyclerView2->
                recyclerView2.layoutManager = layoutManager
                recyclerView2.adapter = adapterComponent

                layoutManager.findFirstVisibleItemPosition()

                recyclerView2.addOnScrollListener(object : RecyclerView.OnScrollListener() {
                    override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                        super.onScrollStateChanged(recyclerView, newState)
                    }

                    override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                        super.onScrolled(recyclerView, dx, dy)
                        //获取RecyclerView当前顶部显示的第一个条目对应的索引
                        val position = layoutManager.findFirstVisibleItemPosition()
                        if (position != adapter.selectPosition) {
                            adapter.selectPosition = position
                            adapter.notifyDataSetChanged()
                        }
                    }
                })
            }

            girdView.setOnItemClickListener { parent, view, position, id ->
                if (isFastClick()) {
                    scroller.scrollToChild(tabContainer)
                    adapter.selectPosition = position
                    adapter.notifyDataSetChanged()
                    layoutManager.scrollToPositionWithOffset(position, 0)
                }
            }
            componentItem.orginDataObject?.let {
                var ratio_x = 1
                var ratio_y = 1
                it.optJSONObject("other_field")?.let {
                    ratio_x = it.optInt("ratio_x")
                    ratio_y = it.optInt("ratio_y")
                }
                adapter.dimensionRatio = "W,${ratio_y}:${ratio_x}"
                val elements = it.optJSONArray("element")
                val size = elements.length()
                val list: MutableList<Item> = ArrayList();
                for (i in 0 until size) {
                    elements.optJSONObject(i)?.let {
                        list.add(Item(it.optString("icon"), it.optString("icon_selected")))
                    }
                }
                adapter.list.clear()
                adapter.list.addAll(list)
                adapter.notifyDataSetChanged()
            }


            adapterComponent?.data = contentList
            adapterComponent?.notifyItemRangeChanged(0, contentList.size)

        }

    }

    override fun f5() {
//        scroller.scrollToChild(tabContainer)
//        scroller.postDelayed({
//            if (activity==null||requireActivity().isFinishing||requireActivity().isDestroyed){
//                return@postDelayed
//            }
//            scroller.scrollY = 0
//        }, 100)
        scroller.scrollToChild(scroller.getChildAt(0))
        refreshLayout.autoRefresh(300)
    }

    override fun gun() {
//        scroller.scrollToChild(tabContainer)
//        scroller.postDelayed({
//            if (activity==null||requireActivity().isFinishing||requireActivity().isDestroyed){
//                return@postDelayed
//            }
//            scroller.scrollY = 0
//        }, 100)
        scroller.scrollToChild(scroller.getChildAt(0))
    }

//
//    class Adapter(val context: Context) : BaseQuickAdapter<Item, BaseViewHolder>(R.layout.item_component89) {
//        var dimensionRatio = "W,9:16"
//        var selectPosition = 0
//        override fun convert(helper: BaseViewHolder, item: Item?) {
//            val logoIv: ImageView = helper.getView(R.id.logoIv)
//
//            if (selectPosition == helper.absoluteAdapterPosition) {
//                logoIv.load(item?.icon_selected, false, ColorDrawable(Color.WHITE))
//            } else {
//                logoIv.load(item?.icon, false, ColorDrawable(Color.WHITE))
//            }
//            val lp = logoIv.layoutParams as ConstraintLayout.LayoutParams
//            lp.dimensionRatio = dimensionRatio
//            logoIv.layoutParams = lp
//
//        }
//    }


    class Adapter(val context: Context) : BaseAdapter() {
        var dimensionRatio = "W,9:16"
        var selectPosition = 0
        val list: MutableList<Item> = ArrayList()
        override fun getCount(): Int {
            return list.size
        }

        override fun getItem(position: Int): Any {
            return list[position]
        }

        override fun getItemId(position: Int): Long {
            return position.toLong()
        }

        override fun getView(position: Int, _convertView: View?, parent: ViewGroup?): View {
            var holder: Holder? = null

            var convertView: View? = _convertView
            if (convertView == null) {
                convertView =
                    LayoutInflater.from(context).inflate(R.layout.item_component89, parent, false);
                holder = Holder()
                holder.logoIv = convertView?.findViewById(R.id.logoIv)
                convertView.tag = holder
            } else {
                holder = convertView.tag as Holder
            }
            val item = list[position]
            if (selectPosition == position) {
                holder.logoIv?.loadX(item.icon_selected, 2, 1, false)
                //holder.logoIv?.load(item.icon_selected, false, ColorDrawable(Color.WHITE))
            } else {
                holder.logoIv?.loadX(item.icon, 2, 1, false)
                //  holder.logoIv?.load(item.icon, false, ColorDrawable(Color.WHITE))
            }
            val lp = holder.logoIv?.layoutParams as ConstraintLayout.LayoutParams
            lp.dimensionRatio = dimensionRatio
            holder.logoIv?.layoutParams = lp
            return convertView!!
        }
    }

    class Holder {
        var logoIv: ImageView? = null
    }

    data class Item(val icon: String?, val icon_selected: String?)

    override fun onDestroyView() {
        fragments.clear()
        for (futureTask in futureTasks) {
            futureTask.isCancelled
        }
        futureTasks.clear()
        moreViews.clear()
        moreViewsCache.clear()
        childFragmentManager.fragments.clear()
        adapterComponent?.destroy()
        componentAdapter?.clearEvent()
        mConsecutiveViewPager?.adapter = null
        mConsecutiveViewPager?.clearOnPageChangeListeners()
        dataInvoker?.destory()
        if(smartRefreshLayout != null){
            smartRefreshLayout.setOnRefreshListener(null)
            smartRefreshLayout.setOnLoadMoreListener(null)
        }
        super.onDestroyView()

        TXReportManager.getInstance().clearThirdAndFourTabInfo()
    }

    private var dataReady = false
    private val app_jhapp_home_subtab_content_impRunable:Runnable = Runnable {
        ExposurePoolService.getExecutorService().execute {
            componentContainer?.let {
                val childCount = componentContainer.getContainer().childCount
                try {
                    for (i in 0 until childCount) {
                        val itemView: View = componentContainer.getContainer().getChildAt(i)
                        //判断View可见了才采集数据
                        if (TXReportManager.getVisibility(itemView)) {
                            var tag: Any? = itemView.getTag(R.id.component3_viewholder)
                            if (tag == null) {
                                tag = itemView.tag
                            }
                            if (tag != null) {
                                if (tag is IExposure) {
                                    val articleItemList = tag.exposureArticles
                                    val componentItem = tag.exposureComponentItem
                                    var componentTitle: String? = ""
                                    if (componentItem != null) {
                                        componentTitle = componentItem.getTitle()
                                    }
                                    titleName = if (TextUtils.isEmpty(componentTitle)){
                                        TXReportManager.getInstance().currentNavigate.tabName
                                    }else {
                                        componentTitle
                                    }
                                    if (articleItemList != null) {
                                        for (k in articleItemList.indices) {
                                            val article = articleItemList[k]
                                            article.positionInList = k
                                           // if (TypeX.COMPONENT.C99996 == componentItem?.width){
                                                CDPTrackReportManager.getInstance().NewsRPExpose(k,article,componentTitle)
                                            //}
                                            TXReportManager.getInstance().app_jhapp_home_subtab_content_imp(
                                                article,
                                                componentItem,
                                                catalogItem
                                            )
                                            TXReportManager.getInstance().app_jhapp_explore_service_cntnt_imp(article,k,titleName)
                                        }
                                    }
                                } else {
                                    if (tag is ComponentHolder) {
                                        //这里是 还没实现IExposure的组件先不管了。遇到了在加
                                        if (BuildConfig.DEBUG) {
                                            Log.w(
                                                "XYADDD",
                                                "未实现IExposure " + tag.javaClass.simpleName
                                            )
                                        }
                                    }
                                }
                            }
                        }
                    }
                    val position = mConsecutiveViewPager?.currentItem ?: 0
                    val fragment = adapter?.getItem(position)
                    if (fragment is IExposure) {
                        val articleItemList = fragment.exposureArticles
                        val componentItem = fragment.exposureComponentItem
                        var componentTitle: String? = ""
                        if (componentItem != null) {
                            componentTitle = componentItem.getTitle()
                        }
                        articleItemList?.let {
                            for (i in 0 until articleItemList.size) {
                                val article= articleItemList[i]
                                article.positionInList = i
                                CDPTrackReportManager.getInstance().NewsRPExpose(i,article)
                                TXReportManager.getInstance().app_jhapp_home_subtab_content_imp(
                                    article,
                                    componentItem,
                                    catalogItem
                                )
                                TXReportManager.getInstance().app_jhapp_explore_service_cntnt_imp(articleItemList[i],i,if (!TextUtils.isEmpty(componentTitle)) componentTitle else catalogItem?.name)
                            }
                        }
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }

        }
    }

    private fun app_jhapp_home_subtab_content_imp(){
        if(!dataReady)return
        scroller?.apply {
            removeCallbacks(app_jhapp_home_subtab_content_impRunable)
            postDelayed(app_jhapp_home_subtab_content_impRunable,TXReportManager.EXPOSURE_DELAY)
        }

    }
}